import {TableCard} from '@/components'
import {Button, Form, Input, Modal, Select} from 'antd'
import {observer} from 'mobx-react'
import React, {useEffect, useState} from 'react'
import store from './store'

// id=1,sn=ck,name=总库,region=[河南省,郑州市,中原区],address=中原路88号
export default observer(function (props) {
  const {onCancel, onOk, searchKey, searchValue} = props
  const [form] = Form.useForm()
  const [selectRows, setSelectRows] = useState([])
  const columns = [{
    title: 'No.',
    key: 'series',
    width: 50,
    render: (_, __, index) => <span className="idx">{index + 1}</span>,
  }, {
    title: '商品名称',
    dataIndex: 'name',
  }, {
    title: '商品编号',
    dataIndex: 'sn',
  }, {
    title: '商品分类',
    render: v => v.category_names?.join(' / '),
  }, {
    title: '规格',
    dataIndex: 'spec',
  }, {
    title: '基本计量单位',
    dataIndex: 'unit',
  }, {
    title: '成本价',
    dataIndex: 'price',
  }]

  useEffect(() => {
    !store.records.length && store.fetchRecords()
  }, [])

  function handleSearch() {
    store.fetchRecords()
  }

  function handleSubmit() {
    onOk(selectRows[0])
  }

  return (
    <Modal
      open
      width={800}
      maskClosable={false}
      title="仓库选择"
      onCancel={onCancel}
      onOk={handleSubmit}>
      <TableCard
        title={
          <Form form={form}
                layout="inline"
                initialValues={{name: searchKey, value: searchValue}}>
            <Form.Item name="name">
              <Select>
                <Select.Option value="name">项目名称</Select.Option>
                <Select.Option value="sn">项目编号</Select.Option>
              </Select>
            </Form.Item>
            <Form.Item name="value">
              <Input/>
            </Form.Item>
          </Form>
        }
        rowKey="id"
        bordered
        loading={store.fetching}
        dataSource={store.dataSource}
        columns={columns}
        pagination={{
          showSizeChanger: true,
          showLessItems: true,
          hideOnSinglePage: false,
          pageSizeOptions: ['10', '20', '50', '100'],
        }}
        rowSelection={{
          columnWidth: 24,
          hideSelectAll: true,
          type: 'radio',
          selectedRowKeys: selectRows.map(v => v.id),
          onSelect: (record, selected, selectedRows) => {
            if (selectedRows.length) {
              setSelectRows(selectedRows)
            } else {
              setSelectRows([])
            }
          },
        }}
        onRow={(record) => ({
          onClick: () => {
            setSelectRows([record])
          },
          onDoubleClick: () => {
            setSelectRows([record])
            onOk(record)
          },
        })}
        actions={[
          <Button type="primary" onClick={handleSearch}>查询</Button>,
        ]}/>
    </Modal>
  )
})
